package com.coderlin.servlet.user;

import com.coderlin.pojo.User;
import com.coderlin.service.user.UserService;
import com.coderlin.service.user.UserServiceImpl;
import com.coderlin.util.Constants;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * <Description> <br>
 *
 * @author Coder_Lin<br>
 * @version 1.0<br>
 * @taskId: <br>
 * @createDate 2021/03/12 22:19 <br>
 * @see com.coderlin.servlet.user <br>
 */
public class LoginServlet extends HttpServlet {



    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("LoginServlet--start......");
        //获取用户名和密码
        String userCode =req.getParameter("userCode");
        String userPassword =req.getParameter("userPassword");


        //和数据库中的密码进行对比，调用业务层
        UserService userService = new UserServiceImpl();
        User user = userService.login(userCode, userPassword);

        /**@see 出现问题，发现user取值为空，之前的单元测试显示Dao层工作正常
         * //System.out.println(user.getAddress());问题解决，原因调用req方法错误，
         * 之前调用的getAttribute方法，应为getParameter
         * */

        //查有此人，可以登录
        if(user!=null){
            //在session中保存用户信息
            req.getSession().setAttribute(Constants.USER_SESSION,user);
            //重定向
            resp.sendRedirect("jsp/frame.jsp");

        }else{
            //设置error信息
            req.setAttribute("error","用户名或密码错误");
            //对请求进行转发
            req.getRequestDispatcher("login.jsp").forward(req,resp);
        }

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
